#include "mylib.h"

void  Init(MyFile *file, int fdd, int flag)
{
    memset(file->buffer, 0, sizeof(file->buffer));
    file->bufferlen = 0;
    file->fd = fdd;
    file->flag = flag;
    file->frush_method=QUANFUSH;
}

MyFile *myfopen(const char *pathname, const char *mode)
{
    
    int flag = -1;
    int st = 1;
    if (strcmp(mode, "w") == 0)
    {
        st = 0;
        flag = O_WRONLY | O_CREAT | O_TRUNC;
    }
    else if (strcmp(mode, "r") == 0)

    {
        flag = O_RDONLY;
    }
    else if (strcmp("a", mode) == 0)
    {
        flag = O_APPEND | O_CREAT | O_WRONLY;
        st = 0;
    }
    else
    {
    }
    int fdd = -1;
    umask(0);
    if (st == 0)
        fdd = open(pathname, flag, 0666);
    else
        fdd = open(pathname, flag);
    if (fdd < 0)
        return NULL;
    MyFile *file = (MyFile *)malloc(sizeof(MyFile));
    Init(file,fdd,flag);
    return file;
}
int myfflush(MyFile *stream)
{
    if(stream->bufferlen<=0) return 0;
    //语言层的刷新其实就是直接写入到内核中
    int n=write(stream->fd,stream->buffer,stream->bufferlen);
    (void)n;
    stream->bufferlen=0;
}
void printfbuff(MyFile*stream)
{
    for(int i=0;i<=stream->bufferlen;i++) printf("%c",stream->buffer[i]);
}
size_t myfwrite(const void *ptr, size_t size, size_t nmemb, MyFile *stream)
{
    //写入本质先拷贝到用户的缓冲区
    memcpy(stream->buffer+stream->bufferlen,ptr,size*nmemb);
    //更新缓冲区长度
    stream->bufferlen+=nmemb*size;
    //考虑是不是要进行刷新到我们的内核缓冲区
    if(stream->fd==1||stream->fd==2) stream->frush_method=LINEFRUSH;
    if(stream->frush_method==LINEFRUSH&&stream->buffer[stream->bufferlen-1]=='\n'||stream->bufferlen==SIZE)
    {
        myfflush(stream);
    }
    //打印缓冲区
    printfbuff(stream);

}
int myfclose(MyFile *stream)
{
    myfflush(stream);
    close(stream->fd);
}
size_t myfread(void *ptr, size_t size, size_t nmemb, MyFile *stream)
{
    char buffer[1024];
    return read(stream->fd,buffer,sizeof(buffer));
}


void add()
{  
    Init(mystdin,0,O_RDONLY);
    Init(mystdout,1,O_RDONLY);
    Init(mystderror,2,O_RDONLY);
}